#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include <string.h>

#define LOG_ERR(fmt, ...) printf("[%s:%d %s]ERR: " fmt "\r\n", __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__);

void* newThreadAction(void* args)
{
    pthread_detach(pthread_self());
    sem_t *sem = args;
    LOG_ERR("this is new thread!");
    LOG_ERR("delay 2s");
    sleep(2);
    int ret = sem_post(sem);
    if (ret != 0) {
        LOG_ERR("sem_post fail ret = %d errno = [%d]%s", ret, errno, strerror(errno));
        return NULL;
    }
    LOG_ERR("sem_post success");
    return NULL;
}

int main()
{
    sem_t sem;
    int ret = sem_init(&sem, 0, 0);
    if (ret != 0) {
        LOG_ERR("sem_init fail ret = %d errno = [%d]%s", ret, errno, strerror(errno));
        return 0;
    }

    pthread_t tid;

    ret = pthread_create(&tid, NULL, newThreadAction, &sem);
    if (ret != 0) {
        LOG_ERR("pthread_create ret = %u", ret);
        return 0;
    }
    LOG_ERR("sem_wait start");
    ret = sem_wait(&sem);
    if (ret != 0) {
        LOG_ERR("sem_wait fail ret = %d errno = [%d]%s", ret, errno, strerror(errno));
        return 0;
    }
    LOG_ERR("sem_wait success");

    sem_destroy(&sem);
    return 0;
}